"""
序列化： 将对象类型转换成json字符串
"""

import json, pickle


# students = [{"id": 101},{"id":102},{"id":103}]

# with open("test.txt", "w") as f:
# 	json.dump(students, f)

# with open("test.pickle", "wb") as f:
# 	pickle.dump(students, f)


# with open("test.txt", "r") as f:
# 	students = json.load(f)
# 	print(len(students))


# with open("test.pickle", "rb") as f:
# 	students = pickle.load(f)
# 	print(len(students))


# 集合 和 自定义数据类型 不能序列化
# json.JSONEncoder  指明序列化规则
# json.JSONDecoder  指明反序列化规则

class Person:
	def __init__(self, name, age):
		self.name = name
		self.age = age


p1 = Person("张三", 20)


class MyJSONEncoder(json.JSONEncoder):
	def default(self, o):
		"""
		:param o: 将要序列化的内容
		:return:  序列化的结果
		"""

		# print(o, type(o))
		if isinstance(o, set):
			return list(o)
		if isinstance(p1, Person):
			return {"name": p1.name, "age": p1.age}
		else:
			return super().default(o)

with open("test.txt", "w", encoding="utf8") as f:
	json.dump(p1, f, cls=MyJSONEncoder, ensure_ascii=False)


class MyJSONDecoder(json.JSONDecoder):
	def decode(self, s: str):
		"""
		:param s: s将要反序列化的内容
		:return:  反序列化的结果
		"""
		# 默认父类的反序列化
		obj = json.loads(s)
		# 加工父类反序列化结果
		p1 = Person(obj["name"], obj["age"])
		return p1


with open("test.txt", "r", encoding="utf8") as f:
	p1 = json.load(f, cls=MyJSONDecoder)
	print(p1, p1.name, p1.age)



